$.extend($.validator.messages, {
    pattern:'Неверный формат',
    required:"Поле обязательно к заполнению",
    email:"Неверный адрес электронной почты",
    minlength:jQuery.validator.format("Допустимая длина - минимум {0} символов.")
    /*remote: "Please fix this field.",
     url: "Please enter a valid URL.",
     date: "Please enter a valid date.",
     dateISO: "Please enter a valid date (ISO).",
     number: "Please enter a valid number.",
     digits: "Please enter only digits.",
     creditcard: "Please enter a valid credit card number.",
     equalTo: "Please enter the same value again.",
     accept: "Please enter a value with a valid extension.",
     maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
     minlength: jQuery.validator.format("Please enter at least {0} characters."),
     rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
     range: jQuery.validator.format("Please enter a value between {0} and {1}."),
     max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
     min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")*/
});

function sliderObject(selector, visibleCount) {
    if ($(selector).length == 0) {
        return;
    }

    var $items = $(selector + ' .contentbox-wrapper .slider-element');
    var currentItem = 1;
    var itemsCount = $items.length;
    var obj = {
        showSliderItem:function (item) {
            $(selector + ' .contentbox-wrapper').animate({"left":-(item.position().left)}, 400);
        }
    };

    var $prevButton = $(selector + ' a.prev');
    $prevButton.addClass('inactive');

    var $nextButton = $(selector + ' a.next');
    if (itemsCount <= visibleCount) {
        $nextButton.addClass('inactive');
    }

    $prevButton.click(function () {
        if ($prevButton.hasClass('inactive')) {
            return;
        }

        $nextButton.removeClass('inactive');

        currentItem--;
        if (currentItem == 1) {
            $prevButton.addClass('inactive');
        }

        obj.showSliderItem($items.eq(currentItem - 1));
    });

    $nextButton.click(function () {
        if ($nextButton.hasClass('inactive')) {
            return;
        }

        $prevButton.removeClass('inactive');

        currentItem++;
        if (currentItem == itemsCount
            || itemsCount <= visibleCount
            || itemsCount - currentItem < visibleCount
            ) {
            $nextButton.addClass('inactive');
        }

        obj.showSliderItem($items.eq(currentItem - 1));
    });
}

function form_input_is_int(input) {
    return !isNaN(input) && parseInt(input) == input;
}

function changeProducts(start, end) {
    var k = 1;

    $(".category-product").each(function () {
        if (k < parseInt(start) || k > parseInt(end)) {
            $(this).hide();
        } else {
            $(this).show();
        }
        k++;
    });
}

function initTextFieldHints() {
    $('.text-hint').each(function () {
        var defaultValue = this.value;
        $(this).focus(function () {
            if ($(this).val() == defaultValue) {
                $(this).val('');
            }
        });
        $(this).blur(function () {
            if ($(this).val() == '') {
                $(this).val(defaultValue);
            }
        });
    });
}

function initUniform() {
    $("#search-block input[type='radio']").uniform();
    $("#right-sidebar input[type='checkbox']").uniform();
    $(".category-page #sorting").uniform();
    $("#right-sidebar #filter-select").uniform();
}

function initSliders() {
    var $priceSlider = $('#price-slider');
    if ($priceSlider.length > 0) {
        var getMinPrice = $.urlParam('arrFilter_P1_MIN');
        var getMaxPrice = $.urlParam('arrFilter_P1_MAX');
        if (getMinPrice == 0) {
            getMinPrice = 100;
        }
        if (getMaxPrice == 0) {
            getMaxPrice = 120000;
        }
        var $minPriceRange = $('#min-price-range');
        var $maxPriceRange = $('#max-price-range');
        $priceSlider.slider({
            range:true,
            min:100,
            max:120000,
            values:[ getMinPrice, getMaxPrice ],
            slide:function (event, ui) {
                $minPriceRange.val(ui.values[ 0 ]);
                $maxPriceRange.val(ui.values[ 1 ]);
            }
        });

        $minPriceRange.val($priceSlider.slider("values", 0));
        $maxPriceRange.val($priceSlider.slider("values", 1));

        $('#min-price-range, #max-price-range').blur(function () {
            $priceSlider.slider("option", "values", [ $minPriceRange.val(), $maxPriceRange.val() ]);
        });
    }

    // init secondary sliders.
    sliderObject('#category-slider', 5);
    sliderObject('#stock-products-slider', 4);
    sliderObject('#best-deals-slider', 4);
    sliderObject('#novelties-slider', 4);
}

function initSorting() {
    $("#sorting").change(function () {
        var selectVal = $(this).val()
        document.location.href = selectVal;
    });
}

function initRightSidebarHints() {
    $('#right-sidebar .hint').click(function () {
        var title = $(this).parent().find('label').text();
        var text = $(this).data('body');

        var elementOffset = $(this).offset();

        var $hintDialog = $("#hint-dialog");
        $hintDialog.empty().html(text);
        $hintDialog.dialog({
            title:title,
            modal:true,
            dialogClass:"modal-hint",
            resizable:false,
            position:{ my:"right+60 top+50", at:"right bottom", of:$(this) }
        });
    });
}

function initProductsPagination() {
    var $paginationBlock = $('#pagination');

    var activePage = $paginationBlock.find(".page.active").attr('data-id');
    var pagesCount = $paginationBlock.find("li").length;

    var $pages = $paginationBlock.find("a");

    //pagination slider
    var $productSlider = $("#product-slider");
    if ($productSlider.length > 0) {
        var slider = $productSlider.slider({
            min:1,
            max:pagesCount,
            width:200,
            range:"min",
            value:activePage,
            slide:function (event, ui) {
                $pages.removeClass('active');
                $pages.filter("[data-id='" + ui.value + "']").addClass('active');

                $(".ui-slider-handle").mouseup(function () {
                    var new_path = $pages.filter("[data-id='" + ui.value + "']").attr('href');
                    document.location.href = new_path;
                });

                /*var end = parseInt(ui.value) * elements_per_page;
                 var start = end - elements_per_page + 1;

                 changeProducts(start,end);*/
            }
        });

        $pages.click(function () {
            $(this).parents('ul').find('a').removeClass('active');
            $(this).addClass('active');
            slider.slider("value", parseInt($(this).text()));
            //return false;
        });
    }
}

function initFilters() {
    var $filterTypeLinks = $('#type-filters li a');
    $filterTypeLinks.click(function () {
        $(this).parent().find('.checkboxes').toggle('fast');
    });
}

function initSmartFilter() {
    var $rightSidebar = $('#right-sidebar');

    var $solutionsContainer = $('#product-solutions-container');
    if ($solutionsContainer.length && !isProductDetailedPage()) {
        $solutionsContainer.remove();
    }

    if ($('#solution-page').length > 0) {
        $rightSidebar.hide();
        return;
    }

    if ($rightSidebar.find('.inner').children().length > 0) {
        $rightSidebar.show();
    } else {
        $rightSidebar.hide();
    }

    var $smartFilter = $(".smartfilter");
    if ($smartFilter.length > 0) {
        $smartFilter.find(".checkboxes li div span").each(function () {
            if ($(this).hasClass("checked")) {
                $(this).parents(".checkboxes").show();
            }
        });
    }
}

function getProductDetailedBlock() {
    return $('#product-detailed-block');
}

function isProductDetailedPage() {
    return getProductDetailedBlock().length > 0;
}

function initPreorderForm() {
    var $container = $('#preorder-container');
    if ($container.length == 0) {
        return;
    }

    $container.find('input[type="text"], textarea').each(function () {
        var placeHolderTextElement = $(this).parent().find('.mf-text');
        placeHolderTextElement.hide();
        var watermark = placeHolderTextElement.text().replace(/^\s\s*/, '').replace(/\s\s*$/, '')/*.replace('*', '')*/;
        $(this).val('').attr('placeholder', watermark);
    });

    var $productBlock = getProductDetailedBlock();
    /*if (
     isProductDetailedPage()
     && (
     $productBlock.attr('data-quantity') == '0'
     && $productBlock.attr('data-price') == '0'
     )
     ) {

     } else {
     // preorder only for products not in stock or with zero price
     $container.remove();
     return;
     }*/

    if (isProductDetailedPage() && $productBlock.attr('data-quantity') != '0')
        $container.remove();


    $container.find('input[type="submit"]').on('click', function () {
        var $message = $container.find('textarea');

        var productUrl = 'http://' + document.location.host + document.location.pathname;
        var text = $message.val();
        if (text.indexOf(productUrl) == -1) {
            text += "\n\n" + 'Предзаказ товара: ' + productUrl;
            $message.val(text);
        }
    });
}

function overrideLangMessages() {
    $('#preorder-container').find('input[type="submit"]').val('Отправить заявку');
    $('.smartfilter').find('input[type="submit"][name="set_filter"]').val('Показать товары');
}

function processProductSolutionsBlock() {
    $('#product-solutions-container').remove();
}

function showPriceHintIfPriceNotUnknown() {
    var $infoBlockForm = $('#product-detailed-block .info form');

    if (isProductDetailedPage() && $('span.price', $infoBlockForm).length == 0)
        $('.warranty').before('' +
            '<span class="price">' +
            '    <strong>Цена:</strong>' +
            '    по запросу' +
            '</span>' +
            '<br/>');
}

$.urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) {
        return 0;
    }
    return results[1] || 0;
}

var registrationForm = {
    init:function () {
        var $form = $("#regform");
        if ($form.length == 0) {
            return;
        }

        $form.validate({
            onkeyup:true,
            errorClass:'error',
            errorPlacement:function (error, element) {
                error.insertAfter(element);
            },
            rules:{
                "REGISTER[LOGIN]":"required",
                "REGISTER[EMAIL]":{
                    required:true,
                    email:true
                },
                "REGISTER[PASSWORD]":{
                    required:true,
                    minlength:6
                },
                "REGISTER[CONFIRM_PASSWORD]":{
                    required:true,
                    equalTo:$('input[name="REGISTER[PASSWORD]"]')
                },
                "REGISTER[PERSONAL_PHONE]":{
                    pattern:'[\+]?[0-9]{7,}'
                },
                "agree":"required",
                "captcha_word":"required"
            },
            messages:{
                "agree":"Вы должны принять пользовательское соглашение",
                "REGISTER[PERSONAL_PHONE]":{
                    pattern:"Неверный формат. Допустимы: цифры и символ \"+\""
                },
                "REGISTER[CONFIRM_PASSWORD]":{
                    equalTo:"Подтверждение должно совпадать с паролем"
                }
            }
        });

        $(".register_submit_button").click(function () {
            if (!$form.valid()) {
                return false;
            }
        });
    }
}

var loginForm = {
    init:function () {
        var $form = $('.header-auth-form');
        if ($form.length == 0) {
            return;
        }

        $('#user-menu').find('.acc-login, .exit').click(function () {
            if ($form.not(':visible')) {
                $form.find('input[name="USER_LOGIN"]').focus();
            }
            $form.toggle('fast');
        });
    },

    show:function () {
        $('.header-auth-form').show();
    }
}

var productProfile = {
    init:function () {
        this.initTabs();
        this.initGallery();
        this.initVotingBlock();
    },

    initTabs:function () {
        var $tabObject = $("#product-description-block");
        if ($tabObject.length > 0) {
            $tabObject.tabs();
            $tabObject.show();
        }
    },

    initGallery:function () {
        var $fancyboxThumbs = $(".fancybox-thumb");
        if ($fancyboxThumbs.length > 0) {
            $fancyboxThumbs.fancybox({
                prevEffect:'none',
                nextEffect:'none',
                helpers:{
                    title:{
                        type:'outside'
                    },
                    thumbs:{
                        width:50,
                        height:50
                    }
                }
            });
        }
    },

    initVotingBlock:function () {
        var $votingBlocks = $(".iblock-vote");
        if ($votingBlocks.length > 0) {
            $votingBlocks.each(function () {
                var rate_value = $(this).attr("title");
                var id = $(this).attr("id").split("_");
                if (!form_input_is_int(rate_value)) {
                    var new_rate_value = rate_value - 0.5;
                    $("#vote_" + id[1] + "_" + new_rate_value).addClass("half-star");
                }
            });
        }
    }
}

var catalogMenu = {
    init:function () {
        this.initMenu('menu-products-catalog');
        this.initMenu('menu-solutions-catalog');
    },

    initMenu:function (containerId) {
        var $container = $('#' + containerId);

        var $markers = $container.find('.catalog-left-menu .category-marker');

        $markers.each(function () {
            if ($(this).siblings('ul').length > 0) {
                $(this).addClass('has-subcategories');
            }
        });

        var $categoryLinks = $markers.filter('.has-subcategories');
        $categoryLinks.click(function () {
            var $subcat = $(this).parent().find('.sub-category');
            if ($subcat.length > 0) {
                $subcat.slideToggle('fast');
                $(this).toggleClass('expanded');
            }
        });
    }
}

$(document).ready(function () {
    initUniform();

    catalogMenu.init();
    loginForm.init();

    initPreorderForm();

    overrideLangMessages();
    processProductSolutionsBlock();
    showPriceHintIfPriceNotUnknown();
});